#!/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header

# 第三方 STMP 服务
# 设置服务器
mail_host = 'smtp.gmail.com'
# 用户名
mail_user = 'tenpy22@gmail.com'
# 口令
mail_pass = 'giroqeoedmhttigf'
# 发件人
sender = 'tenpy22@gmail.com'
# 收件人
receivers = ['tenpy22@gmail.com']

message = MIMEMultipart('related')

# 发件人
message['From'] = Header("菜鸟教程", 'utf-8')
# 收件人
message['To'] = Header("测试", 'utf-8')
# 邮件主题
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')

msgAlternative = MIMEMultipart('alternative')
message.attach(msgAlternative)

mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.runoob.com">菜鸟教程链接</a></p>
<p>图片演示：</p>
<p><img src="cid:image1"></p>
"""
# 邮件内容
msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))

# 指定图片为当前目录
fp = open('test.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()

# 定义图片 ID，在 HTML 文本中引用
msgImage.add_header('Content-ID', '<image1>')
message.attach(msgImage)

try:
    smtpObj = smtplib.SMTP()
    # Google的SMTP端口号
    smtpObj.connect(mail_host, 587)
    smtpObj.ehlo()  # 向Gamil发送SMTP 'ehlo' 命令
    smtpObj.starttls()
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print('邮件发送成功')
except:
    print('Error: 无法发送邮件')